package com.sias.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.UUID;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hy.corecode.idgen.WFGIdGenerator;
import com.sias.common.exception.MyException;
import com.sias.common.result.ResultCodeEnum;
import com.sias.entity.dto.LoginDto;
import com.sias.entity.dto.UserDetailsDto;
import com.sias.entity.dto.UserDto;
import com.sias.entity.pojo.User;
import com.sias.entity.pojo.UserDetails;
import com.sias.entity.pojo.VipUser;
import com.sias.entity.vo.LoginVo;
import com.sias.entity.vo.TeacherVo;
import com.sias.entity.vo.UserDetailsVo;
import com.sias.entity.vo.UserVo;
import com.sias.mapper.UserMapper;
import com.sias.service.UserDetailsService;
import com.sias.service.UserService;
import com.sias.service.VipUserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
* @author chf
* @description 针对表【user】的数据库操作Service实现
* @createDate 2024-07-05 10:34:28
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{

    // 雪花算法
    @Autowired
    private WFGIdGenerator wFGIdGenerator;


    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private VipUserService vipUserService;


    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Override
    public int saveUserDetails(UserDetailsDto userDetailsDto) {
       boolean success =  baseMapper.exists(new LambdaQueryWrapper<User>().eq(User::getUsername,userDetailsDto.getUsername()));
        if (success){
            throw new MyException(ResultCodeEnum.USER_NAME_IS_EXISTS);
        }
        //密码加密
        String password = userDetailsDto.getPassword();
        if (StringUtils.isEmpty(password)){
            throw new MyException(ResultCodeEnum.DATA_ERROR);
        }
        User user = new User();
        BeanUtil.copyProperties(userDetailsDto,user);
        String id=String.valueOf(wFGIdGenerator.next());
        user.setId(id);
        Date now = new Date();
        user.setUpdateTime(now);
        user.setFristtime(now);
        user.setIsDelete("0");
        user.setPassword(DigestUtils.md5DigestAsHex(password.getBytes()));
        baseMapper.insert(user);
        //用户详情表
        UserDetails userDetails = new UserDetails();
        BeanUtil.copyProperties(userDetailsDto,userDetails);
        userDetails.setId(id);
        userDetailsService.save(userDetails);
        //用户金额表
        VipUser vipUser = new VipUser();
        vipUser.setId(id);
        vipUser.setAllcase(0);
        vipUser.setMycase(0);
        vipUser.setVip("0");
        vipUser.setVipDeatils("0");
        vipUserService.save(vipUser);
        return 1;
    }

    @Override
    public LoginVo login(LoginDto loginDto) {
        // 根据用户名查询用户
        User user = baseMapper.selectOne(new QueryWrapper<User>()
                .eq("username", loginDto.getUserName())
                .eq("is_delete", "0"));
        if(user == null) {
            throw new MyException(ResultCodeEnum.LOGIN_ERROR) ;
        }

        // 验证密码是否正确
        String inputPassword = loginDto.getPassword();
        String md5InputPassword = DigestUtils.md5DigestAsHex(inputPassword.getBytes());
        if(!md5InputPassword.equals(user.getPassword())) {
            throw new RuntimeException("用户名或者密码错误") ;
        }

        // 生成令牌，保存数据到Redis中
        String token = UUID.randomUUID().toString().replace("-", "");
        redisTemplate.opsForValue().set("user:login:" + token , JSON.toJSONString(user) , 30 , TimeUnit.MINUTES);

        // 构建响应结果对象
        LoginVo loginVo = new LoginVo() ;
        loginVo.setToken(token);
        loginVo.setRefresh_token("");

        // 返回
        return loginVo;
    }

    @Override
    public User getUserInfo(String token) {
        String userJson = redisTemplate.opsForValue().get("user:login:" + token);
        return JSON.parseObject(userJson , User.class) ;
    }

    @Override
    public Page<UserVo> listAll(UserDto userDto, Integer pageNum, Integer pageSize) {
        Page page = new Page<>(pageNum, pageSize);


        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getIsDelete, "0");
        //有条件时
        if (!StringUtils.isEmpty(userDto.getNickname())){
            wrapper.like(User::getNickname, userDto.getNickname());
        }
        Page<User> userList = baseMapper.selectPage(page, wrapper);

        Page<UserVo> userVoList =new Page<>();
        userVoList.setPages(userList.getPages())
                .setCurrent(userList.getCurrent())
                .setSize(userList.getSize())
                .setTotal(userList.getRecords().size())
                .setRecords(BeanUtil.copyToList(userList.getRecords(), UserVo.class));


        return userVoList;

    }

    @Override
    public UserDetailsVo selectById(String userId) {
           UserDetailsVo userDetailsVo = new UserDetailsVo();
        if (userId != null) {
            User user = baseMapper.selectById(userId);
            if (!user.getIsDelete().equals("0")){
                throw new MyException(ResultCodeEnum.ACCOUNT_STOP);
            }
            UserDetails userDetails = userDetailsService.getById(userId);
            BeanUtil.copyProperties(userDetails,userDetailsVo);
            BeanUtil.copyProperties(user,userDetailsVo);
            return userDetailsVo;
        }
        throw new RuntimeException("数据异常");
    }

    @Override
    public int updateUserDetailsVip(UserDetailsDto userDetailsDto) {
        boolean success =  baseMapper.exists(new LambdaQueryWrapper<User>().eq(User::getUsername,userDetailsDto.getUsername()));
        if (success){
            throw new MyException(ResultCodeEnum.USER_NAME_IS_EXISTS);
        }
        UserDetails userDetails = new UserDetails();
        BeanUtil.copyProperties(userDetailsDto,userDetails);
        boolean istrue= userDetailsService.updateById(userDetails);
        User user = new User();
        BeanUtil.copyProperties(userDetailsDto,user);
        int i =  baseMapper.updateById(user);
        if (!istrue){
            throw new MyException(ResultCodeEnum.DATA_ERROR);
        }
        if (i<=0){
            throw new MyException(ResultCodeEnum.DATA_ERROR);
        }
        return 1;

    }

    //查询所有讲师
    @Override
    public List<TeacherVo> selectTeacher() {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUserRole,"2");
        wrapper.eq(User::getIsDelete,"0");
        List<User> userList =  baseMapper.selectList(wrapper);
        List<TeacherVo> teacherVos = BeanUtil.copyToList(userList, TeacherVo.class);
        return teacherVos;
    }

    //逻辑删除删除用户
    @Override
    public int deleteUser(String userId) {
        User user = new User();
        user.setId(userId);
        user.setIsDelete("1");
        baseMapper.updateById(user);
        return 1;
    }


}




